// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.SupplierOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.SupplierOrderMapper;
import com.fowo.api.mapper.SupplierOrderProductMapper;
import com.fowo.api.mapper.SupplierOrderProductStepMapper;
import com.fowo.api.model.supplier.order.SupplierOrderExcelPo;
import com.fowo.api.model.supplier.order.SupplierOrderImportPo;
import com.fowo.api.model.supplier.order.SupplierOrderItemVo;
import com.fowo.api.model.supplier.order.SupplierOrderSearchParamPo;
import com.fowo.api.model.supplier.order.SupplierOrderVo;
import com.fowo.api.model.supplier.order.constant.SupplierOrderAnStatusEnums;
import com.fowo.api.model.supplier.order.constant.SupplierOrderArrivalStatusEnums;
import com.fowo.api.model.supplier.order.constant.SupplierOrderFeePartTypeEnums;
import com.fowo.api.model.supplier.order.constant.SupplierOrderIncludingTaxEnums;
import com.fowo.api.model.supplier.order.constant.SupplierOrderPayStatusEnums;
import com.fowo.api.model.supplier.order.constant.SupplierOrderUrgentOrNotEnums;
import com.fowo.api.model.supplier.order.product.SupplierOrderProductSearchParamPo;
import com.fowo.api.model.supplier.order.product.step.SupplierOrderProductStepSearchParamPo;
import com.fowo.api.service.SupplierOrderProductService;
import com.fowo.api.service.SupplierOrderProductStepService;
import com.fowo.api.service.SupplierOrderService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 供应商订单 服务实现类
 * @author 蜂窝蜜造平台 配置人：周计鑫，任凯
 */
@Service
@Slf4j
@DataObjectType(SupplierOrder.class)
@DS("ds24")
public class SupplierOrderServiceImpl
  extends ServiceImpl<SupplierOrderMapper, SupplierOrder>
  implements SupplierOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("contactPersonName", "su.`name`");
      put("optUidName", "su2.`name`");
      put("oversightUidName", "su3.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected SupplierOrderService self;

  @Resource
  protected SupplierOrderProductService supplierOrderProductService;

  @Resource
  protected SupplierOrderProductStepService supplierOrderProductStepService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建供应商订单
   * @param model 供应商订单
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SupplierOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrder entity = new SupplierOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getSupplierOrder())) {
      entity.setSupplierOrder(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "SupplierOrder.supplierOrder")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("供应商订单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 供应商订单
   */
  protected void updateAllChilds(SupplierOrderVo model) throws Exception {
    if (model.getPurchaseOrde() != null) {
      supplierOrderProductService.saveAllByParentSupplierOrder(
        model.getId(),
        model.getPurchaseOrde()
      );
    }

    if (model.getProduct() != null) {
      supplierOrderProductService.saveAllByParentSupplierOrder(
        model.getId(),
        model.getProduct()
      );
    }

    if (model.getStep() != null) {
      supplierOrderProductStepService.saveAllByParentSupplierOrder(
        model.getId(),
        model.getStep()
      );
    }
  }

  /**
   * 更新供应商订单
   * @param model 供应商订单
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SupplierOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商订单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "optUid",
      "oversightUid",
      "totalPrice"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新供应商订单（带空值）
   * @param model 供应商订单
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SupplierOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商订单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(SupplierOrder::getSupplierOrder, model.getSupplierOrder())
      .set(SupplierOrder::getSupplierId, model.getSupplierId())
      .set(SupplierOrder::getSupplierName, model.getSupplierName())
      .set(SupplierOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(SupplierOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(SupplierOrder::getPurchaseOrderCode, model.getPurchaseOrderCode())
      .set(SupplierOrder::getContactPerson, model.getContactPerson())
      .set(SupplierOrder::getContactNumber, model.getContactNumber())
      .set(SupplierOrder::getSettlementMethod, model.getSettlementMethod())
      .set(SupplierOrder::getAdvanceRatio, model.getAdvanceRatio())
      .set(SupplierOrder::getSettlementDescribe, model.getSettlementDescribe())
      .set(SupplierOrder::getPaymentMethod, model.getPaymentMethod())
      .set(SupplierOrder::getPurchaseCurrency, model.getPurchaseCurrency())
      .set(SupplierOrder::getShippingPrice, model.getShippingPrice())
      .set(SupplierOrder::getOtherCurrency, model.getOtherCurrency())
      .set(SupplierOrder::getFeePartType, model.getFeePartType())
      .set(SupplierOrder::getIncludingTax, model.getIncludingTax())
      .set(SupplierOrder::getRemarks, model.getRemarks())
      .set(SupplierOrder::getQuantityReceived, model.getQuantityReceived())
      .set(SupplierOrder::getStauts, model.getStauts())
      .set(SupplierOrder::getPurchasesDate, model.getPurchasesDate())
      .set(SupplierOrder::getPurchaseQuantity, model.getPurchaseQuantity())
      .set(SupplierOrder::getAnStatus, model.getAnStatus())
      .set(SupplierOrder::getOrderRemarkSear, model.getOrderRemarkSear())
      .set(
        model.getFile() != null,
        SupplierOrder::getFile,
        JSON.toJSONString(model.getFile())
      )
      .setSql(model.getFile() == null, "file = null")
      .set(SupplierOrder::getArrivalStatus, model.getArrivalStatus())
      .set(SupplierOrder::getOrderTime, model.getOrderTime())
      .set(SupplierOrder::getPayStatus, model.getPayStatus())
      .set(SupplierOrder::getUrgentOrNot, model.getUrgentOrNot())
      .eq(SupplierOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(SupplierOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 采购详情(purchaseOrde) 对应的对象
    SupplierOrderProductSearchParamPo purchaseOrdeSearchParam =
      new SupplierOrderProductSearchParamPo();
    purchaseOrdeSearchParam.setDisableDataPremissions(true);
    purchaseOrdeSearchParam.setParentSupplierOrderInList(ids);
    SupplierOrderProductMapper localSupplierOrderProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(SupplierOrderProductMapper.class);
    purchaseOrdeSearchParam.applySqlSegments();
    List<Long> purchaseOrdeIdList = localSupplierOrderProductMapper.searchIds(
      purchaseOrdeSearchParam
    );
    if (!purchaseOrdeIdList.isEmpty()) {
      SupplierOrderProductService localSupplierOrderProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(SupplierOrderProductService.class);
      localSupplierOrderProductService.batchDelete(purchaseOrdeIdList);
    }

    // 处理子表字段 商品(product) 对应的对象
    SupplierOrderProductSearchParamPo productSearchParam =
      new SupplierOrderProductSearchParamPo();
    productSearchParam.setDisableDataPremissions(true);
    productSearchParam.setParentSupplierOrderInList(ids);
    productSearchParam.applySqlSegments();
    List<Long> productIdList = localSupplierOrderProductMapper.searchIds(
      productSearchParam
    );
    if (!productIdList.isEmpty()) {
      SupplierOrderProductService localSupplierOrderProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(SupplierOrderProductService.class);
      localSupplierOrderProductService.batchDelete(productIdList);
    }

    // 处理子表字段 进度(step) 对应的对象
    SupplierOrderProductStepSearchParamPo stepSearchParam =
      new SupplierOrderProductStepSearchParamPo();
    stepSearchParam.setDisableDataPremissions(true);
    stepSearchParam.setParentSupplierOrderInList(ids);
    SupplierOrderProductStepMapper localSupplierOrderProductStepMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(SupplierOrderProductStepMapper.class);
    stepSearchParam.applySqlSegments();
    List<Long> stepIdList = localSupplierOrderProductStepMapper.searchIds(
      stepSearchParam
    );
    if (!stepIdList.isEmpty()) {
      SupplierOrderProductStepService localSupplierOrderProductStepService =
        ContextHolder
          .getApplicationContext()
          .getBean(SupplierOrderProductStepService.class);
      localSupplierOrderProductStepService.batchDelete(stepIdList);
    }
  }

  /**
   * 删除供应商订单
   * @param id 供应商订单的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除供应商订单
   * @param ids 供应商订单的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<SupplierOrderImportPo> excelToImportRow(
    SupplierOrderImportPo row,
    Integer rowNumber,
    SupplierOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<SupplierOrderImportPo> ir =
      new ImportRow<SupplierOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<SupplierOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new SupplierOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, SupplierOrderImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getSettlementMethod())) {
      List<SysDictAllItem> settlementMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "settlementMethod",
          n -> sysDictService.getDictItems("SCM00004")
        );
      SupplierOrderVo finalVo = vo;
      settlementMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSettlementMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSettlementMethod(i.getItemValue()),
          () ->
            ir.addError(
              "settlementMethod",
              String.format(
                "必须为 %s 中之一",
                settlementMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setAdvanceRatio(SheetUtils.tryToDecimal(row.getAdvanceRatio()));
    if (StringUtils.hasText(row.getPaymentMethod())) {
      List<SysDictAllItem> paymentMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "paymentMethod",
          n -> sysDictService.getDictItems("SCM00005")
        );
      SupplierOrderVo finalVo = vo;
      paymentMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPaymentMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPaymentMethod(i.getItemValue()),
          () ->
            ir.addError(
              "paymentMethod",
              String.format(
                "必须为 %s 中之一",
                paymentMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPurchaseCurrency())) {
      List<SysDictAllItem> purchaseCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "purchaseCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      SupplierOrderVo finalVo = vo;
      purchaseCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPurchaseCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPurchaseCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "purchaseCurrency",
              String.format(
                "必须为 %s 中之一",
                purchaseCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setShippingPrice(SheetUtils.tryToDecimal(row.getShippingPrice()));
    vo.setOtherCurrency(SheetUtils.tryToDecimal(row.getOtherCurrency()));
    if (StringUtils.hasText(row.getFeePartType())) {
      vo.setFeePartType(
        SupplierOrderFeePartTypeEnums.toValue(row.getFeePartType())
      );
      if (vo.getFeePartType() == null) {
        ir.addError(
          "feePartType",
          "费用分摊方式只能是：“不分摊”, “按金额”, “按数量”"
        );
      }
    }
    if (StringUtils.hasText(row.getIncludingTax())) {
      vo.setIncludingTax(
        SupplierOrderIncludingTaxEnums.toValue(row.getIncludingTax())
      );
      if (vo.getIncludingTax() == null) {
        ir.addError("includingTax", "含税只能是：“否”, “是”");
      }
    }
    vo.setTotalPrice(SheetUtils.tryToDecimal(row.getTotalPrice()));
    vo.setQuantityReceived(SheetUtils.tryToInteger(row.getQuantityReceived()));
    if (StringUtils.hasText(row.getStauts())) {
      List<SysDictAllItem> stautsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "stauts",
          n -> sysDictService.getDictItems("SCM00020")
        );
      SupplierOrderVo finalVo = vo;
      stautsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStauts()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStauts(i.getItemValue()),
          () ->
            ir.addError(
              "stauts",
              String.format(
                "必须为 %s 中之一",
                stautsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setPurchasesDate(SheetUtils.tryToDate(row.getPurchasesDate()));
    SheetUtils.datePreviewFormat(row.getPurchasesDate(), row::setPurchasesDate);
    vo.setPurchaseQuantity(SheetUtils.tryToInteger(row.getPurchaseQuantity()));
    if (StringUtils.hasText(row.getAnStatus())) {
      vo.setAnStatus(SupplierOrderAnStatusEnums.toValue(row.getAnStatus()));
      if (vo.getAnStatus() == null) {
        ir.addError(
          "anStatus",
          "审批状态只能是：“作废”, “待提交”, “待到货”, “已完成”, “待审批”, “驳回”"
        );
      }
    }
    if (StringUtils.hasText(row.getArrivalStatus())) {
      vo.setArrivalStatus(
        SupplierOrderArrivalStatusEnums.toValue(row.getArrivalStatus())
      );
      if (vo.getArrivalStatus() == null) {
        ir.addError(
          "arrivalStatus",
          "发货状态只能是：“未到货”, “部分到货”, “全部到货”"
        );
      }
    }
    vo.setOrderTime(SheetUtils.tryToDateTime(row.getOrderTime()));
    if (StringUtils.hasText(row.getPayStatus())) {
      vo.setPayStatus(SupplierOrderPayStatusEnums.toValue(row.getPayStatus()));
      if (vo.getPayStatus() == null) {
        ir.addError(
          "payStatus",
          "付款状态只能是：“未申请”, “已申请”, “部分付款”, “已付款”"
        );
      }
    }
    if (StringUtils.hasText(row.getUrgentOrNot())) {
      vo.setUrgentOrNot(
        SupplierOrderUrgentOrNotEnums.toValue(row.getUrgentOrNot())
      );
      if (vo.getUrgentOrNot() == null) {
        ir.addError("urgentOrNot", "加急只能是：“是”, “否”");
      }
    }
    // 处理关联字段“联系人”
    if (
      !SheetUtils.isBlank(row.getContactPersonName()) &&
      SheetUtils.isBlank(row.getContactPerson())
    ) {
      SysUserSearch contactPersonSearchParam = new SysUserSearch();
      contactPersonSearchParam.setLimit(2); // 最大只返回二行记录
      contactPersonSearchParam.setNameEq(
        SheetUtils.trim(row.getContactPersonName())
      );
      contactPersonSearchParam.applySqlSegments();
      List<SysUserItemVo> contactPersonMatches = sysUserMapper.search(
        contactPersonSearchParam
      );
      if (contactPersonMatches.size() == 0) {
        ir.addError("contactPersonName", "未能在用户中找到匹配的数据");
      } else if (contactPersonMatches.size() > 1) {
        ir.addError(
          "contactPersonName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setContactPerson(contactPersonMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购员”
    if (
      !SheetUtils.isBlank(row.getOptUidName()) &&
      SheetUtils.isBlank(row.getOptUid())
    ) {
      SysUserSearch optUidSearchParam = new SysUserSearch();
      optUidSearchParam.setLimit(2); // 最大只返回二行记录
      optUidSearchParam.setNameEq(SheetUtils.trim(row.getOptUidName()));
      optUidSearchParam.applySqlSegments();
      List<SysUserItemVo> optUidMatches = sysUserMapper.search(
        optUidSearchParam
      );
      if (optUidMatches.size() == 0) {
        ir.addError("optUidName", "未能在用户中找到匹配的数据");
      } else if (optUidMatches.size() > 1) {
        ir.addError("optUidName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setOptUid(optUidMatches.get(0).getId());
      }
    }
    // 处理关联字段“单据负责人”
    if (
      !SheetUtils.isBlank(row.getOversightUidName()) &&
      SheetUtils.isBlank(row.getOversightUid())
    ) {
      SysUserSearch oversightUidSearchParam = new SysUserSearch();
      oversightUidSearchParam.setLimit(2); // 最大只返回二行记录
      oversightUidSearchParam.setNameEq(
        SheetUtils.trim(row.getOversightUidName())
      );
      oversightUidSearchParam.applySqlSegments();
      List<SysUserItemVo> oversightUidMatches = sysUserMapper.search(
        oversightUidSearchParam
      );
      if (oversightUidMatches.size() == 0) {
        ir.addError("oversightUidName", "未能在用户中找到匹配的数据");
      } else if (oversightUidMatches.size() > 1) {
        ir.addError(
          "oversightUidName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setOversightUid(oversightUidMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<SupplierOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<SupplierOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            SupplierOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              SupplierOrderImportPo row,
              AnalysisContext cxt
            ) {
              SupplierOrderVo vo = new SupplierOrderVo();
              ImportRow<SupplierOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<SupplierOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<SupplierOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      SupplierOrderVo vo = new SupplierOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "supplierOrder".equals(m.getField())
          )
      ) {
        vo.setSupplierOrder(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "SupplierOrder.supplierOrder")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    SupplierOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "contactPerson",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SupplierOrderItemVo) r).getContactPersonName())
          )
      );
      exportOptions.addFieldMappingOption(
        "settlementMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00004")
      );
      exportOptions.addFieldMappingOption(
        "paymentMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00005")
      );
      exportOptions.addFieldMappingOption(
        "purchaseCurrency",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "feePartType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SupplierOrderFeePartTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "includingTax",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SupplierOrderIncludingTaxEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "optUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SupplierOrderItemVo) r).getOptUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "oversightUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SupplierOrderItemVo) r).getOversightUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "stauts",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00020")
      );
      exportOptions.addFieldMappingOption(
        "purchasesDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "anStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> SupplierOrderAnStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "arrivalStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SupplierOrderArrivalStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "payStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SupplierOrderPayStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "urgentOrNot",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            SupplierOrderUrgentOrNotEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "supplierOrder",
        "purchaseOrderCode",
        "contactPersonName",
        "contactNumber",
        "settlementMethod",
        "settlementDescribe",
        "paymentMethod",
        "purchaseCurrency",
        "feePartType",
        "includingTax",
        "optUidName",
        "oversightUidName",
        "remarks",
        "stauts",
        "anStatus",
        "orderRemarkSear",
        "arrivalStatus",
        "payStatus",
        "urgentOrNot"
      );

      String fileName = String.format(
        "供应商订单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> settlementMethodItems = sysDictService.getDictItems(
      "SCM00004"
    );
    List<SysDictAllItem> paymentMethodItems = sysDictService.getDictItems(
      "SCM00005"
    );
    List<SysDictAllItem> purchaseCurrencyItems = sysDictService.getDictItems(
      "SCM00015"
    );
    List<SysDictAllItem> stautsItems = sysDictService.getDictItems("SCM00020");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SupplierOrderExcelPo> items = new ArrayList<SupplierOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<SupplierOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SupplierOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SupplierOrderItemVo item : list) {
        SupplierOrderExcelPo excel = new SupplierOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getSettlementMethod() != null) {
          settlementMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSettlementMethod()))
            .findFirst()
            .ifPresent(i -> excel.setSettlementMethod(i.getItemText()));
        }
        if (item.getPaymentMethod() != null) {
          paymentMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPaymentMethod()))
            .findFirst()
            .ifPresent(i -> excel.setPaymentMethod(i.getItemText()));
        }
        if (item.getPurchaseCurrency() != null) {
          purchaseCurrencyItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPurchaseCurrency()))
            .findFirst()
            .ifPresent(i -> excel.setPurchaseCurrency(i.getItemText()));
        }
        excel.setFeePartType(
          SupplierOrderFeePartTypeEnums.toLabel(item.getFeePartType())
        );
        excel.setIncludingTax(
          SupplierOrderIncludingTaxEnums.toLabel(item.getIncludingTax())
        );
        if (item.getStauts() != null) {
          stautsItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStauts()))
            .findFirst()
            .ifPresent(i -> excel.setStauts(i.getItemText()));
        }
        excel.setAnStatus(
          SupplierOrderAnStatusEnums.toLabel(item.getAnStatus())
        );
        excel.setArrivalStatus(
          SupplierOrderArrivalStatusEnums.toLabel(item.getArrivalStatus())
        );
        excel.setPayStatus(
          SupplierOrderPayStatusEnums.toLabel(item.getPayStatus())
        );
        excel.setUrgentOrNot(
          SupplierOrderUrgentOrNotEnums.toLabel(item.getUrgentOrNot())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "供应商订单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SupplierOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过单号查询供应商订单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySupplierOrder(String supplierOrder) {
    return this.baseMapper.getIdBySupplierOrder(supplierOrder);
  }

  /**
   * 通过单号查询供应商订单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySupplierOrder(List<String> list) {
    return this.baseMapper.getIdsBySupplierOrder(list);
  }

  /**
   * 通过供应商订单主键查询单号
   */
  @Override
  public String getSupplierOrderById(Long id) {
    return this.baseMapper.getSupplierOrderById(id);
  }

  /**
   * 通过供应商订单主键查询单号列表
   */
  @Override
  public List<String> getSupplierOrderByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getSupplierOrderByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("supplierOrder"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 供应商订单的主键
   */
  @Override
  public SupplierOrderVo getVoById(Long id) throws Exception {
    SupplierOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    SupplierOrderProductSearchParamPo purchaseOrdeSearchParamPo =
      new SupplierOrderProductSearchParamPo();
    purchaseOrdeSearchParamPo.setParentSupplierOrder(id);
    purchaseOrdeSearchParamPo.getExtendData().put("queryMode", "sub");
    purchaseOrdeSearchParamPo
      .getExtendData()
      .put("queryParent", "SupplierOrder");
    purchaseOrdeSearchParamPo.applySqlSegments();
    vo.setPurchaseOrde(
      supplierOrderProductService.search(purchaseOrdeSearchParamPo)
    );

    SupplierOrderProductSearchParamPo productSearchParamPo =
      new SupplierOrderProductSearchParamPo();
    productSearchParamPo.setParentSupplierOrder(id);
    productSearchParamPo.getExtendData().put("queryMode", "sub");
    productSearchParamPo.getExtendData().put("queryParent", "SupplierOrder");
    productSearchParamPo.applySqlSegments();
    vo.setProduct(supplierOrderProductService.search(productSearchParamPo));

    SupplierOrderProductStepSearchParamPo stepSearchParamPo =
      new SupplierOrderProductStepSearchParamPo();
    stepSearchParamPo.setParentSupplierOrder(id);
    stepSearchParamPo.getExtendData().put("queryMode", "sub");
    stepSearchParamPo.getExtendData().put("queryParent", "SupplierOrder");
    stepSearchParamPo.applySqlSegments();
    vo.setStep(supplierOrderProductStepService.search(stepSearchParamPo));

    return vo;
  }

  /**
   * 分页查询供应商订单
   * @param search 查询条件
   * @return 供应商订单分页查询结果
   */
  @Override
  public Page<SupplierOrderItemVo> pageSearch(
    SupplierOrderSearchParamPo search
  ) {
    Page<SupplierOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SupplierOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 供应商订单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SupplierOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SupplierOrderItemVo>> searchOptions(
    SupplierOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询供应商订单
   * @param search 查询条件
   * @return 供应商订单列表查询结果
   */
  @Override
  public List<SupplierOrderItemVo> search(SupplierOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询供应商订单最后更新时间
   * @param search 查询条件
   * @return 供应商订单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SupplierOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
